package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * projectName: com.atguigu.lease.web.admin.custom.converter
 *
 * @author: 赵伟风
 * description: 批量制造转化器
 */

//枚举转化器工厂！ 批量制造转化器
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    //制造转化器的方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体转化器
        return new Converter<String, T>() {
            //定义转化方法
            @Override
            public T convert(String source) {
                //1. 获取枚举的全部值
                //ItemType.values(); //枚举的.values获取全部值
                //2. 循环获取枚举的getCode 和 source对象
                for (T enumConstant : targetType.getEnumConstants()) {
                    //3. 如何相同直接返回类型
                    if (enumConstant.getCode() == Integer.parseInt(source)){
                        return enumConstant;
                    }
                }
                //4. 循环以后没有抛出异常
                throw  new RuntimeException("非法类型异常！！");
            }
        };
    }
}
